<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        // print_r(model('app\admin\model\User')->getStateList());die;
//        $statusList=model('app\admin\model\User')->getStateList();
        $statusList=[0=>"普通用户",1=>"学校社团团长",2=>"分销商"];
        $this->view->assign("statusList", $statusList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法

//        $this->error($data);
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $this->error($where);
            $list = $this->model
                ->with(['group','level','recommend','viptype'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                // print_r($v['viptype']);die;
         
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                // if($v->isvip==0){
                //     $v['viptype']['name'] = '普通会员';
                //     // print_r($v->viptype);die;
                // }
 
                
                // print_r($v['recommend']->nickname);
                // die;
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            $user=$this->model->get($params['id']);
            if($user['vip_id']!=$params['vip_id']){
                $data = [
                    'order_sn'=>'',
                    'user_id'=>$params['id'],
                    'goods_id'=>$params['vip_id'],
                    'createtime'=>time(),
                    'status'=>2,
                    ];
                model('app\admin\model\Ordermember')->insert($data);
            }
            
            
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('vipList', build_select('row[vip_id]', \app\admin\model\Membertype::column('id,name'), $row['vip_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    //操作
    public function recommend($ids = null){


        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            // $this->token();
            $params = $this->request->post('row/a');
            //   var_dump($params);exit();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
            // $this->token();
            $number = $params['number']; //充值

            if ($number<0) {
                $this->error('次数需大于0');
            }

            $status = $params['status']; //状态


            if($number > 0){
                $log = '管理员增加余额';
                if($status == 'hidden'){ //增加
//                    $number = $number;
                    $row->recommend_num = $row->recommend_num - $number;
                    $number_text = 0-$number;
                }else{
                    $row->recommend_num = $row->recommend_num + $number;
                    $number_text = $number;
                }

                Db::startTrans();
                try {

                    $bool = $row->save();

                    $bool2 = model('app\common\model\Recommend')->save(
                        ['user_id'   => $params['id'],
                        'number'    => $number_text,
                        'last_num'  => $row->recommend_num,
                        'state'     =>1,
                        'mote'      =>$params['memo'],
                        'to_user_id'=>0,
                        'createtime'=>time(),]);

                    if($bool && $bool2){
                        Db::commit();
                    }else {
                        Db::rollback();
                        $this->error('操作失败');
                    }


                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error('增加失败');
                }
                $this->success('成功');

            }else{
                $this->error('请填写数量');
            }

        }


        $this->view->assign('row',$row);
        return $this->view->fetch();
    }


    //操作
    public function levelnum($ids = null){


        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            // $this->token();
            $params = $this->request->post('row/a');
            //   var_dump($params);exit();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
            // $this->token();
            $number = $params['number']; //充值

            if ($number<0) {
                $this->error('次数需大于0');
            }

            $status = $params['status']; //状态


            if($number > 0){
                $log = '管理员增加余额';
                if($status == 'hidden'){ //增加
//                    $number = $number;
                    $row->level_num = $row->level_num - $number;
                    $number_text = 0-$number;
                }else{
                    $row->level_num = $row->level_num + $number;
                    $number_text = $number;
                }

                Db::startTrans();
                try {

                    $bool = $row->save();

                    $bool2 = model('app\common\model\Levelnum')->save(
                        ['user_id'   => $params['id'],
                            'number'    => $number_text,
                            'last_num'  => $row->level_num,
                            'state'     =>1,
                            'mote'      =>$params['memo'],
                            'to_user_id'=>0,
                            'createtime'=>time(),]);

                    if($bool && $bool2){
                        Db::commit();
                    }else {
                        Db::rollback();
                        $this->error('操作失败');
                    }


                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error('增加失败');
                }
                $this->success('成功');

            }else{
                $this->error('请填写数量');
            }

        }


        $this->view->assign('row',$row);
        return $this->view->fetch();
    }


//

}
